package Web;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wuhan
 * @date 2019/10/20 17:14
 *
 *      *
 *      *
 *      * 开工！！！@date 10/21
 *      *
 *      *
 *      */
public class Login {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("172.20.10.11",10008);
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

        for (int i = 0; i < 3; i++) {
            String line = bufr.readLine();
            if (line==null){
                break;
            }
            out.println(line);
            String info = bufIn.readLine();

            System.out.println("info:"+info);
            if (info.contains("欢迎")){
                break;
            }
        }
        bufr.close();
        s.close();
    }
}

class UserThread implements Runnable{
    private Socket socket;

    public UserThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            String IP = socket.getInetAddress().getHostAddress();
            System.out.println(IP+"...connected");
            for (int i = 0; i < 3; i++) {
                BufferedReader bufIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String name = bufIn.readLine();
                if (name==null){
                    break;
                }
                BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));
                PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
                String line = null;
                boolean flag = false;
                while ((line=bufr.readLine())!=null){
                    if (line.equals(name)){
                         flag = true;
                    }
                }
                if (flag==true){
                    System.out.println(name+",已登陆");
                    out.println(name+"欢迎光临");
                    break;

                }else {
                    System.out.println(name+"尝试登陆");
                    out.println(name+",用户名不存在");
                }
                socket.close();
            }
        }catch (Exception e){
            throw new RuntimeException("校验失败");
        }
    }
}

class LoginServer{
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10008);
        while (true){
            Socket socket   = ss.accept();
            new Thread(new UserThread(socket)).start();
        }
    }
}
